﻿using EntityFramework.Caching;
using EntityFramework.Extensions;
using Newtonsoft.Json;
using RXY_Mall.Api.Common;
using RXY_Mall.Api.Models;
using RXY_Mall.Core;
using RXY_Mall.Core.Tool;
using RXY_Mall.Data;
using RXY_Mall.Domain;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Http;
using WebApi.OutputCache.V2;


namespace RXY_Mall.Api.Controllers
{
    /// <summary>
    /// 营销接口
    /// </summary>
    [RoutePrefix("Marketing")]
    public class MarketingController : BaseApiController
    {
        private RXY_MallContext db = new RXY_MallContext();
        /// <summary>
        /// 缓存时间 单位s
        /// </summary>
        public const int CACHETIME = 300;

        /// <summary>
        /// 获取Banners（第2批）
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("GetBanners")]
        [CacheOutput(ClientTimeSpan = CACHETIME, ServerTimeSpan = CACHETIME)]
        public async Task<Response<List<GetBannersOutput>>> GetBanners(int user_id = 0)
        {
            Response<List<GetBannersOutput>> result = new Response<List<GetBannersOutput>>();
            result.code = 1;
            result.data = null;

            try
            {
                var banners = await db.gw_marketing_banners
                    .Where(t => t.status == 1 && (t.company_id == CompanyId || t.company_id == null))
                    .Select(item => new GetBannersOutput()
                    {
                        picture_url = item.picture_url,
                        title = item.title,
                        content = item.content,
                        sort = item.sort,
                        advert_type = (AdvertType)item.type
                    }).ToListAsync();

                foreach (var item in banners)
                {
                    item.picture_url = HostHelper.GetImgUrl(item.picture_url);
                }
                result.code = 1;
                result.data = banners;
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
                result.code = 2;
                LogHelper.WriteLog(ex);
            }

            return result;
        }

        /// <summary>
        /// 获取首页商品（第2批）
        /// </summary>
        /// <returns></returns>
        /// <param name="user_id"></param>
        /// <param name="page_index">页码 1=>第1页</param>
        /// <param name="page_size">页数 20=>每页20条数据</param>
        [HttpGet]
        [Route("GetHomeGoods")]
        [CacheOutput(ClientTimeSpan = CACHETIME, ServerTimeSpan = CACHETIME)]
        public Response<IPagedList<GetGoodsListOutput>> GetHomeGoods(int user_id = 0, int page_index = 1, int page_size = 20)
        {
            Response<IPagedList<GetGoodsListOutput>> result = new Response<IPagedList<GetGoodsListOutput>>();
            result.code = 1;
            result.data = null;

            try
            {
                var now = DateTime.Now;

                var marketingGoodsBank = db.gw_marketing_goods
                    .Include(m => m.gw_goods)
                    .Include(m => m.gw_goods.gw_goods_property)
                    .Include(m => m.gw_goods.gw_goods_picture)
                    .Include(m => m.gw_goods.gw_goods_sku)
                    .Include(m => m.gw_goods.gw_cart)
                    .Where(t => t.status == 1 && t.gw_goods.deleted == false && t.gw_goods.gw_goods_property.published == 1 && t.company_id == CompanyId)
                    .OrderBy(a => a.sort);

                if (marketingGoodsBank == null || marketingGoodsBank.Count() == 0)
                {
                    result.msg = "未获取到商品广告";
                    return result;
                }

                var source = marketingGoodsBank.Select(g => new GetGoodsListOutput
                {
                    shop_id = g.gw_goods.shop_id,
                    category_id = (int)g.gw_goods.category_id,
                    goods_type = (GoodsType)g.gw_goods.type_id,
                    goods_id = g.gw_goods.id,
                    goods_name = g.gw_goods.name,
                    goods_spec = g.gw_goods.spec,
                    goods_brand = g.gw_goods.gw_base_brand.name,
                    goods_mnemonic = g.gw_goods.mnemonic,
                    sort = g.gw_goods.gw_goods_property.sort,
                    add_time = g.gw_goods.add_time,
                    market_price = g.gw_goods.gw_goods_property.market_price,
                    sale_price = g.gw_goods.gw_goods_property.sale_price,
                    picture_url = g.gw_goods.gw_goods_picture.FirstOrDefault(p => p.is_default == true && p.type == 0).url,
                    sale_count = g.gw_goods.gw_goods_property.sale_count,
                    is_top = g.gw_goods.gw_goods_property.is_top,
                    is_sale = g.gw_goods.gw_goods_property.is_sale,
                    is_new = g.gw_goods.gw_goods_property.is_new,
                    goods_collection = g.gw_goods.gw_goods_collection.FirstOrDefault(c => c.user_id == user_id),
                    skus = g.gw_goods.gw_goods_sku
                           .Where(s => !s.deleted)
                           .Select(s => new SkuOutput()
                           {
                               sku_id = s.id,
                               is_sale = s.is_sale,
                               limit_quantity = s.limit_quantity,
                               market_price = s.market_price,
                               sale_price = s.sale_price,
                               cost_price = s.settlement_price,
                               json_specs = s.specs,
                               thumb_url = s.thumb_url,
                               quantity = 0,
                           }).ToList(),
                    cart = g.gw_goods.gw_cart
                            .Where(c => c.user_id == user_id)
                            .Select(s => new CartOutput()
                            {
                                cart_id = s.id,
                                quantity = s.quantity,
                                sku_id = s.sku_id,
                            }).ToList(),
                });
                source = source.OrderBy(s => s.sort);
                IPagedList<GetGoodsListOutput> output = new PagedList<GetGoodsListOutput>(source, page_index, page_size);

                foreach (var item in output)
                {
                    item.picture_url = HostHelper.GetImgUrl(item.picture_url);
                    if (item.goods_collection != null)
                    {
                        item.goods_collection_id = item.goods_collection.id;
                    }

                    if (item.skus != null && item.skus.Count > 0)
                    {
                        foreach (var sku in item.skus)
                        {
                            if (item.cart != null)
                            {
                                var cart = item.cart.FirstOrDefault(c => c.sku_id == sku.sku_id);
                                if (cart != null)
                                {
                                    sku.quantity = cart.quantity;
                                    sku.cart_id = cart.cart_id;
                                }
                            }
                            sku.thumb_url = HostHelper.GetImgUrl(sku.thumb_url);
                            sku.specs = JsonConvert.DeserializeObject<List<SpecOutput>>(sku.json_specs);
                        }
                    }
                }

                result.code = 1;
                result.msg = "获取成功";
                result.data = output;
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
                result.code = 2;
                LogHelper.WriteLog(ex);
            }

            return result;
        }

        /// <summary>
        /// 首页=bannner+推荐品牌+推荐分类
        /// </summary>
        [HttpGet]
        [Route("GetHomeData")]
        [CacheOutput(ClientTimeSpan = 5, ServerTimeSpan = 5)]
        public async Task<Response<GetHomeGoodsOutput>> GetHomeData(int user_id = 0)
        {
            var result = new Response<GetHomeGoodsOutput>();
            result.code = 0;
            result.data = new GetHomeGoodsOutput();

            try
            {
                var banners = await GetBanners(user_id);
                if (banners.code == 1)
                {
                    result.data.banners = banners.data;
                }

                var goods = new GoodsController();
                goods.CompanyId = CompanyId;
                goods.UserId = UserId;
                var brands = await goods.GetBrands(user_id);
                if (brands.code == 1)
                {
                    result.data.top_brands = brands.data.Take(6).ToList();
                }

                var categories = await goods.GetCategories(user_id);
                if (categories.code == 1)
                {
                    result.data.top_categories = categories.data.Take(6).ToList();
                }

                result.code = 1;
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
                result.code = 2;
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        #region 优惠券        
        /// <summary>
        /// 优惠券列表(第2批)
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("GetCoupons")]
        [CacheOutput(ClientTimeSpan = 1, ServerTimeSpan = 1)]
        public Response<IPagedList<GetCouponOutput>> GetCoupons(CouponType coupons_type = CouponType.Ordinary, int page_index = 1, int page_size = 20)
        {
            Response<IPagedList<GetCouponOutput>> result = new Response<IPagedList<GetCouponOutput>>();
            result.code = 0;
            result.data = null;

            try
            {
                var now = DateTime.Now;
                var source = db.gw_marketing_coupons
                    .Where(t => t.deleted == false && t.status == 1 && t.start_date < now && t.end_date > now);
                if (coupons_type != CouponType.All)
                {
                    source = source.Where(t => t.type == (int)coupons_type);
                }
                var sourceCoupons = source.Select(t => new GetCouponOutput()
                {
                    _end_date = t.end_date,
                    _start_date = t.start_date,

                    coupon_id = t.id,
                    name = t.name,
                    amount = t.amount,
                    value = t.value,
                    type = t.type,
                    sort = t.sort,
                    remain_quantity = t.remain_quantity,
                    total_quantity = t.total_quantity,
                    is_all = t.is_all,
                });
                sourceCoupons = sourceCoupons.Where(t => t.coupon_id != 84).OrderBy(t => t.sort).ThenBy(t => t.amount);

                IPagedList<GetCouponOutput> output = new PagedList<GetCouponOutput>(sourceCoupons, page_index, page_size);
                foreach (var item in output)
                {
                    item.coupon_type = (CouponType)item.type;
                    item.end_date = TimeHelper.GetTimeStamp(item._end_date);
                    item.start_date = TimeHelper.GetTimeStamp(item._start_date);
                }
                result.code = 1;
                result.data = output;
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
                result.code = 2;
                LogHelper.WriteLog(ex);
            }

            return result;
        }

        #endregion

    }
}
